package quik.group;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import comm.util.QuikFileRenamePolicy;
import comm.util.QuikHashMap;
import comm.util.RequestManager;
import comm.util.SqlMapLoader;

public class GroupProc {
	public GroupProc() {	}
	
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	
	public String changeName(HttpServletRequest request) throws UnsupportedEncodingException{
		String result = "";
		QuikHashMap hm = RequestManager.getRequest(request);
		hm.put("GROUP_SEQ",request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		if(hm.get("GROUP_NAME").toString().trim().length()>0){
			try {
				sqlMapper.update("group.changeName",hm);
				result = "SUCCESS";
			} catch (SQLException e) {
				result = "FAIL";
				e.printStackTrace();
			}
		}else{
			result = "FAIL";
		}
		return result;
	}
	
	public String imgUpload(HttpServletRequest request,String savePath){
		String result="";
		HashMap hm = new HashMap();
		File f = new File(savePath);
		f.mkdir();
		System.out.println(savePath);
		int sizeLimit = 5 * 1024 * 1024 ; // 5메가까지 제한 넘어서면 예외발생
		try{
			MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit,"UTF-8", new QuikFileRenamePolicy());
		 	Enumeration formNames=multi.getFileNames();  // 폼의 이름 반환
			String formName=(String)formNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
			String fileName=multi.getFilesystemName(formName); // 파일의 이름 얻기

		    if(fileName == null) { // 파일이 업로드 되지 않았을때
		        
		    } else { // 파일이 업로드 되었을때
	    		System.out.println("업로드 성공 :"+fileName);
		        fileName=new String(fileName);
		        hm.put("GROUP_SEQ", request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
		        hm.put("GROUP_IMG", fileName);
		        sqlMapper.update("group.imgUpload",hm);
		        result = "SUCCESS";
		    } // end if
		} catch(Exception e) {
		    System.out.print("예외 상황 발생..! "+e.getMessage());
		    result = "FAIL";
		}
		return result;
	}
	
	public String getCurImg(HttpServletRequest request){
		String result = "";
		try {
			String file = (String) sqlMapper.queryForObject("group.getCurImg",request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ").toString());
			result = "./data/groupImage/"+request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ")+"/"+file;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public String getCurImg(String curGroupSeq){
		String result = "";
		
		try {
			String file = (String) sqlMapper.queryForObject("group.getCurImg",curGroupSeq);
			if(file.equals("")) result = "";
			else result = "/data/groupImage/"+curGroupSeq+"/"+file;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/*	여기서 부터는 회사내 그룹 ( Inner 그룹을 위한 메소드들 )
	 *	###############################################################################
	 */
	
	public String genNewInnerGroup(HttpServletRequest request,String savePath){
		String result="";
		
		
			HashMap hm = new HashMap();
			File f = new File(savePath);
			f.mkdir();
			System.out.println(savePath);
			int sizeLimit = 6 * 1024 * 1024 ; // 6메가까지 제한 넘어서면 예외발생
			try{
				MultipartRequest multi=new MultipartRequest(request, savePath, sizeLimit,"UTF-8", new QuikFileRenamePolicy());
			 	Enumeration formFileNames=multi.getFileNames();  // 폼의 이름 반환
			 	Enumeration formNames = multi.getParameterNames();
			 	
			 	String formFileName = (String)formFileNames.nextElement(); // 자료가 많을 경우엔 while 문을 사용
				String fileName = multi.getFilesystemName(formFileName); // 파일의 이름 얻기
				String formName = null;
				while(formNames.hasMoreElements()){
						formName = (String) formNames.nextElement();
						System.out.println(formName+"///////"+multi.getParameter(formName));
						hm.put(formName.toUpperCase(), multi.getParameter(formName).toString());
				}
	
			    if(fileName == null) { // 파일이 업로드 되지 않았을때
			    	result = "NOFILE";
			    } else { // 파일이 업로드 되었을때
		    		System.out.println("업로드 성공 :"+fileName);
			        fileName=new String(fileName);
			        hm.put("GROUP_SEQ",request.getSession().getAttribute("SESSION_MEMBER_GROUPSEQ"));
			        hm.put("MEMBER_SEQ",request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
			        hm.put("GROUP_IMG", fileName);
			        
			        if(checkValidateInnerGroupName((String) hm.get("GROUP_NAME")).equals("SUCCESS")){
			        	sqlMapper.insert("group.regInnerGroup",hm);
			        	String curInnerGroupSeq = (String)sqlMapper.queryForObject("group.getRecentRegInnerGroupSeq",request.getSession().getAttribute("SESSION_MEMBER_SEQ"));
			        	hm.put("INNERGROUP_SEQ", curInnerGroupSeq);
			        	sqlMapper.insert("group.regInnerGroupRelation",hm);
				        result = "SUCCESS";
					}else{
						result = "DUPLICATED";
					}
			    } // end if
			    
			} catch(Exception e) {
			    System.out.print("예외 상황 발생..! "+e.getMessage());
			    result = "FAIL";
			}
		return result;
	}
	
	public String checkValidateInnerGroupName(String str){
		String result = "";
		try {
			result = (String)sqlMapper.queryForObject("group.checkInnerGroupName",str);
			if(result.equals("0")){
			result = "SUCCESS";
			}else{
				result="DUPLICATED";
			}
		} catch (SQLException e) {
			result = "ERROR";
			e.printStackTrace();
		}
		return result;
	}
	
	public ArrayList getMembersGroupList(String str){
		ArrayList lt = null;
		try {
			lt = (ArrayList)sqlMapper.queryForList("group.getMembersGroupList",str);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	
	public ArrayList getMembersGroupArticleList(String str,String group_seq,int pageSize,int curPage){
		ArrayList lt = null;
		QuikHashMap hm = new QuikHashMap();
		int _pageSize = 15;
		int _curPage = 1;
		
		if(pageSize>0)
			_pageSize = pageSize;
		if(curPage>0)
			_curPage = curPage;
		
		hm.put("INNERGROUP_SEQ", str);
		hm.put("FROM_NUMBER", ((_curPage)-1)*(_pageSize));
		hm.put("TO_NUMBER", (_curPage)*(_pageSize));
		hm.put("GROUP_SEQ", group_seq);
		
		try {
			lt = (ArrayList)sqlMapper.queryForList("group.getMembersGroupArticleList",hm);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	
	public ArrayList getMembersGroupInfo(String str){
		ArrayList lt = null;
		try {
			lt = (ArrayList)sqlMapper.queryForList("group.getMembersGroupInfo",str);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	
	public ArrayList getCurGroupsInnerGroup(String str,String pageSize,String curPage){
		ArrayList lt = null;
		QuikHashMap hm = new QuikHashMap();
		String _pageSize = "15";
		String _curPage = "1";
		
		if(pageSize!=null)
			_pageSize = pageSize;
		if(curPage!=null)
			_curPage = curPage;
		
		hm.put("GROUP_SEQ", str);
		hm.put("FROM_NUMBER", (Integer.parseInt(_curPage)-1)*Integer.parseInt(_pageSize));
		hm.put("TO_NUMBER", Integer.parseInt(_curPage)*Integer.parseInt(_pageSize));
		try {
			lt = (ArrayList)sqlMapper.queryForList("group.getCurGroupsInnerGroup",hm);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lt;
	}
	public String outGroup(HttpServletRequest request) throws UnsupportedEncodingException{
		String result = "FAIL";
		QuikHashMap hm = new QuikHashMap();
		hm = RequestManager.getRequest(request);
		hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ").toString());
		
		try {
			sqlMapper.delete("group.outGroup",hm);
			result = "SUCCESS";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return result;
		}
		
		return result;
	}
	
	public String joinGroup(HttpServletRequest request) throws UnsupportedEncodingException{
		String result = "FAIL";
		QuikHashMap hm = new QuikHashMap();
		hm = RequestManager.getRequest(request);
		hm.put("MEMBER_SEQ", request.getSession().getAttribute("SESSION_MEMBER_SEQ").toString());
		
		try {
			sqlMapper.insert("group.joinGroup",hm);
			result = "SUCCESS";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return result;
		}
		
		return result;
	}
}
